package com.neurotech.pcc.dummy

import android.arch.lifecycle.LiveData
import android.arch.persistence.room.*
import android.content.Context
import java.io.Serializable

/**
 * Created by shenhua on 2018/10/12.
 * @author shenhua
 *         Email shenhuanet@126.com
 */
@Entity(tableName = "remotes")
class RemoteModel() : Serializable {

    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "_id")
    var id: Int? = null
    @ColumnInfo(name = "_host")
    var host: String? = null
    @ColumnInfo(name = "_port")
    var port: String? = null
    @ColumnInfo(name = "_alias")
    var alias: String? = null
    @ColumnInfo(name = "_mac")
    var mac: String? = null
    @ColumnInfo(name = "_color")
    var color: Int? = null
    @ColumnInfo(name = "_group")
    var group: String? = null
    @ColumnInfo(name = "_update_time")
    var time: Long = System.currentTimeMillis()

    @Ignore
    constructor(host: String, port: String, alias: String, mac: String) : this() {
        this.host = host
        this.port = port
        this.alias = alias
        this.mac = mac
    }

    @Ignore
    override fun toString(): String {
        return "RemoteModel(id=$id, host=$host, port=$port, alias=$alias, mac=$mac, color=$color, group=$group, time=$time)"
    }

}

@Dao
interface RemoteDao {

    @Query("SELECT * FROM remotes")
    fun getAllRemotes(): LiveData<List<RemoteModel>>

    @Query("SELECT * FROM remotes WHERE _group = :group")
    fun getRemotesByGroup(group: String): LiveData<List<RemoteModel>>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertRemotes(remoteModel: RemoteModel)

    @Update
    fun updateRemote(remoteModel: RemoteModel)

    @Query("DELETE FROM remotes WHERE _id = :id")
    fun deleteRemotes(id: Int)
}

@Database(entities = [RemoteModel::class], version = 1, exportSchema = false)
abstract class RemotesDatabase : RoomDatabase() {

    abstract fun remoteDao(): RemoteDao

    companion object {
        private var instance: RemotesDatabase? = null
        fun getInstance(context: Context): RemotesDatabase {
            if (instance == null) {
                instance = Room.databaseBuilder(context.applicationContext,
                        RemotesDatabase::class.java,
                        "remotes.db").build()
            }
            return instance as RemotesDatabase
        }
    }
}